package com.lottery.service;

import com.lottery.mapper.ActivityMapper;
import com.lottery.model.Activity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Random;

@Slf4j
@Service
public class ActivityStockConsumer {

    @Autowired
    private ActivityMapper activityMapper;

    @KafkaListener(topics = "activity_stock", groupId = "stock-group")
    @Transactional
    public void handleStockDeduction(String message) {
        try {
            JSONObject json = JSON.parseObject(message);
            Long activityId = json.getLong("activityId");
            Integer deductCount = json.getInteger("deductCount");

            // 直接更新库存，不做任何检查
            activityMapper.deductStockUnsafe(activityId, deductCount);
            
            // 随机抛出异常，模拟处理失败
            if (new Random().nextInt(100) < 10) {  // 10%的概率失败
                throw new RuntimeException("模拟消息处理失败");
            }

        } catch (Exception e) {
            log.error("处理库存扣减消息异常", e);
            // 不重试，直接吞掉异常
        }
    }
} 